import { MethodType, createAlova } from 'alova';
import adapterFetch from 'alova/fetch';
import { history } from "umi"

interface AnyObject extends Record<string, any> { }

export interface IAlovaConfig {
    url: string;
    method: MethodType;
    params?: AnyObject;
    data?: AnyObject;
    cacheFor?: any
}


const alovaInstance = createAlova({
    requestAdapter: adapterFetch(),
    // 关闭缓存模式
    cacheFor: null,
    responded: async (response) => {
        const res = await response.json()
        if (res.code === 401) {
            localStorage.clear()
            history.replace({ pathname: '/login' })
        }
        return res
    },
    timeout: 10000,
    beforeRequest: (method) => {
        const userId = localStorage.getItem("userId");
        if (userId) {
            method.config.headers['userId'] = userId
        }
    }
});

/**
 * options
 * @params url
 * @params method
 * @params data
 */
class HttpSerive {
    constructor() { }
    request<T extends AnyObject>(options: IAlovaConfig): Promise<T> {
        if (options.method.toLocaleLowerCase() == 'get') {
            options.params = options.data;
            Reflect.deleteProperty(options, 'data')
        }
        return new Promise((res, rej) => {
            alovaInstance.Request<T, any>({
                ...options,
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Request-Headers': '*',
                }
            }).then(response => {
                const { code, data, msg } = response
                res(data)
            }).catch(err => rej(err))
        })
    }
}

export default new HttpSerive()